﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.Common;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Models.Admin;
using DHQGHN.PM0.Controllers;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.MVC.Controllers;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class UserInGroupController : BaseController
    {
        UserInGroupBO userInGroupBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(UserInGroupController));

        public ActionResult Index(UserInGroupModel m = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", int currentId = -1)
        { 
            try
            {
                SetActiveMenu("/UserInGroup/Index");
                if (m == null) m = new UserInGroupModel();
                m.GroupId = -1;
                var model = search(m, pageIndex, currentId, false);
                //ViewBag.lstGroup = getListGroup();
                ViewBag.lstApp = CommonData.getListApp();
                ViewBag.lstGroupUser = getGroupUserListHeader();
                return View("~/Views/UserInGroup/UserInGroup.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// Hiển thị form thêm mới chức năng
        [HttpPost]
        public ActionResult actionPrepareCreateOrUpdateUserInGroup(int? id, int groupID, int AppId)
        {
            try
            {
                UserInGroupModel model = null;
                if (groupID > -1)
                {
                    if (id != null && id > -1)
                    {
                        userInGroupBO = new UserInGroupBO();
                        model = new UserInGroupModel(userInGroupBO.GetUserInGroupById(id));
                    }
                    if (model == null)
                    {
                        model = new UserInGroupModel()
                        {
                            UserInGroupId = -1,
                            UserId = -1,
                            GroupId = groupID,
                            //Descriptions = "",
                            IsActive = 1
                        };
                    }
                    ViewBag.lstAppID = AppId;
                    ViewBag.lstApp = CommonData.getListApp();
                    ViewBag.lstGroup = getListGroup(AppId);
                    ViewBag.lstUser = getActiveUserByGroupId(getListUser(AppId), getListUserInGroupByGroupId(groupID, AppId));
                    if (Request.IsAjaxRequest())
                    {
                        return PartialView("~/Views/UserInGroup/_UserInGroupModels.cshtml", model);
                    }
                }
                return View(model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(UserInGroupModel aModel = null, int pageIndex = 0, string sort = "UserInGroupId", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                if (aModel == null) aModel = new UserInGroupModel();
                
                var model = new DataPage<UserInGroupModel>();
                while (model.Data.Count() == 0 && pageIndex >= 0)
                {
                    model = search(aModel, pageIndex, currentId, false);
                    pageIndex--;
                }
                //ViewBag.lstGroup = getListGroup(-1);
                ViewBag.groupId = aModel.GroupId.ToString();
                return PartialView("~/Views/UserInGroup/_UserInGroupList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionSearchname(UserInGroupModel aModel = null, string SeatchParam = null, int groupID = 0, int AppId = -1)
        {
            try
            {
                if (aModel == null) aModel = new UserInGroupModel();
                
                ViewBag.lstUser = getActiveUserByGroupId(getListUser(-1), getListUserInGroupByGroupId(groupID, AppId));
                var j = ViewBag.lstUser;
                var t = j.Items.Count;
                //ViewBag.h=null;
                if (SeatchParam == "")
                {
                    //ViewBag.lstGroup = getListGroup(-1);
                    ViewBag.lstUser = getActiveUserByGroupId(getListUser(-1), getListUserInGroupByGroupId(groupID, AppId));
                    return PartialView("~/Views/UserInGroup/_TableList.cshtml");
                }
                else
                {
                    List<SelectListItem> lstResult = new List<SelectListItem>();
                    string upperSeatchParam = SeatchParam.ToUpper();
                    for (int i = 0; i < t; i++)
                    {
                        if ((j.Items[i].Text).ToUpper().IndexOf(upperSeatchParam, System.StringComparison.OrdinalIgnoreCase) != -1)
                        //if ((j.Items[i].Text).ToUpper().Contains(upperSeatchParam))
                        {
                            lstResult.Add(new SelectListItem() { Text = j.Items[i].Text, Value = j.Items[i].Value });
                        }
                    }
                    //ViewBag.lstGroup = getListGroup(-1);
                    ViewBag.lstUser = new SelectList(lstResult);
                    return PartialView("~/Views/UserInGroup/_TableList.cshtml");
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }


        /// Thêm mới người dùng
        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult actionCreateOrUpdateUserInGroup(UserInGroupModel model, int[] listID)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    userInGroupBO = new UserInGroupBO();
                    bool result = userInGroupBO.createOrUpdateUserInGroup(model.toDALModel(), listID);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            LogStream.GetJsonString<UserInGroupModel>(model) +
                            CommonData.GetListId("Danh sách UserId: ", ";", listID),
                            Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateUserInGroup");

                        if (model.UserInGroupId != null && model.UserInGroupId > -1)
                        {
                            return Json(JsonResponse.Json200("Thêm mới người dùng thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Thêm mới người dùng thành công!"));
                        }
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(int[] id)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    userInGroupBO = new UserInGroupBO();
                    bool result = userInGroupBO.deleteUserInGroup(id);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(id),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");

                        return Json(JsonResponse.Json200("Xóa người dùng thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        private DataPage<UserInGroupModel> search(UserInGroupModel myModel, int pageIndex, int currentId, bool compareEqual)
        {
            try
            {
                userInGroupBO = new UserInGroupBO();
                var models = new DataPage<UserInGroupModel>();
                var DALModel = userInGroupBO.GetDynamicListPaging(myModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.UserInGroupModel gender in lstItem)
                {
                    models.Data.Add(new UserInGroupModel(gender));
                }

                UserInGroupModel model = null;
                if (currentId >= 0 && models.Data.Count > 0)
                {
                    model = models.Data.Find(user => user.UserInGroupId == currentId);
                    models.CustomData = model;
                }
                else
                {
                    models.CustomData = myModel;
                }
                if (models.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "UserInGroup",
                        CurrentPage = pageIndex,
                        InputSearchId = "",
                        TagetReLoadId = "user-in-group-list",

                    };
                    pagNative.TotalRows = models.Data[0].RecordCount;
                    pagNative.CurrentRow = models.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return models;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private List<UserModel> getListUser(int? AppId)
        {
            UserBO userBO = new UserBO();
            var lstUser = userBO.GetAll(AppId);
            List<UserModel> lstItems = new List<UserModel>();
            foreach (var user in lstUser)
            {
                lstItems.Add(new UserModel(user));
            }
            return lstItems;
        }


        //Get all menu in a role of database
        private Dictionary<int, int> getListUserInGroupByGroupId(int groupId, int? AppId)
        {
            try
            {
                userInGroupBO = new UserInGroupBO();
                Dictionary<int, int> lstUser = new Dictionary<int, int>();
                var lstItems = userInGroupBO.GetListUserInGroupByGroupId(groupId, AppId);
                foreach (var user in lstItems)
                {
                    lstUser.Add(user.UserId, user.GroupId);
                }
                return lstUser;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<SelectListItem> getListGroup(int? AppId)
        {
            try
            {
                GroupBO GroupBO = new GroupBO();
                var lstType = GroupBO.GetAll(AppId);
                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = "-1",
                    Text = "Chọn nhóm"
                });
                foreach (var type in lstType)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = type.GroupId.ToString(),
                        Text = type.GroupName
                    });
                }

                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<SelectListItem> getActiveUserByGroupId(List<UserModel> lstUser, Dictionary<int, int> lstUserInGroup)
        {
            try
            {
                List<SelectListItem> lstItems = new List<SelectListItem>();

                foreach (var user in lstUser)
                {
                    if (!lstUserInGroup.ContainsKey(user.ID))
                    {
                        lstItems.Add(new SelectListItem
                        {
                            Value = user.ID.ToString(),
                            Text = user.UserName
                        });
                    }
                }
                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }


        public JsonResult CheckExistUserInGroup(UserInGroupModel userInGroupModel)
        {
            try
            {
                if (userInGroupModel == null) return Json("Chưa có giá trị");
                var model = search(userInGroupModel, 0, 0, true);
                if (model.Data.Any())
                {
                    return Json(Resources.Localization.UserInGroupExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public JsonResult GetListGroupByApp(int AppId)
        {
            try
            {
                GroupBO GroupBO = new GroupBO();
                var lstType = GroupBO.GetListGroupByApp(AppId);
                List<SelectListItem> lstItems = new List<SelectListItem>();
                foreach (var type in lstType)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = type.GroupId.ToString(),
                        Text = type.GroupName
                    });
                }

                return Json(new SelectList(lstItems, "Value", "Text"));
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<SelectListItem> getListApp()
        {
            try
            {
                ApplicationBO appBO = new ApplicationBO();
                var lstType = appBO.GetAll();
                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = "0",
                    Text = "Chọn tên ứng dụng"
                });
                foreach (var type in lstType)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = type.AppId.ToString(),
                        Text = type.AppName
                    });
                }

                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<SelectListItem> getGroupUserListHeader()
        {
            List<SelectListItem> lstItems = new List<SelectListItem>();
            lstItems.Add(new SelectListItem
            {
                Value = "-1",
                Text = "Chọn nhóm"
            });
            return new SelectList(lstItems, "Value", "Text");
        }

        private string GetFunction()
        {
            return "Phân người dùng vào nhóm - UserInGroupController";
        }
    }
}